//封装axios
import axios from 'axios'
import router from '@/router/index.js'
import {ElMessage} from "element-plus";

let token = 'ssl';
//创建axios
const requset = axios.create({
    baseURL: "http://localhost:8080", //端口号
    withCredentials: false, //配置请求接口跨域时是否需要凭证
    timeout: 10000, //超时时间 10s
});
//配置请求头参数类型，和编码格式
axios.defaults.headers["Content-Type"] = "application/json?charset=utf-8"
//配置请求的拦截器
requset.interceptors.request.use((config) => {
        //在请求头中添加token
        //TODO: token应该在pinia中获取
        if (token) {
            config.headers['Authorization'] = token
        }
        return config;
    }, (error) => {
        //发生异常
        console.log("请求异常:", error)
        return Promise.reject(error)
    }
)


//配置响应
requset.interceptors.response((response) => {
        let {msg, code} = response.data
        console.log("code:", code, "msg:", msg)
        if (code == null) {
            return response;
        } else if (code == 200) {
            return response;
        } else if (code == 500) {
            ElMessage.error('服务器异常！')
        } else if (code == 401) {
            ElMessage.error('没有操作权限！')
        } else if (code == 403) {
            ElMessage.error('登录过期！')
            window.sessionStorage.clear()
            router.push("/login")
        }
        return Promise.reject(msg)
    }, (error) => {
        //出现异常
        ElMessage.error("error:", error)
        window.sessionStorage.clear()
        router.push("/login")
    }
)

//导出
export default requset
